package com.scujj.controller.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.scujj.controller.OrderGoodsController;
import com.scujj.pojo.Goods;
import com.scujj.pojo.OrderGoods;
import com.scujj.pojo.Result;
import com.scujj.pojo.User;
import com.scujj.service.GoodsService;
import com.scujj.service.OrderGoodsService;
import com.scujj.service.UserService;
import com.scujj.util.GoodStatusUtil;
import com.scujj.util.OrderGoodsStatusUtil;
import com.scujj.util.PageUtil;
import com.scujj.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;

@RestController
@RequestMapping("/orderGoods")
@Api(tags = "订单api")
public class OrderGoodsControllerImpl implements OrderGoodsController {
    @Autowired
    private OrderGoodsService orderGoodsService;
    @Autowired
    private GoodsService goodsService;
    @Autowired
    private UserService userService;

    @Override
    @GetMapping("/getOrderByUid")
    @ApiOperation("根据买家id获取订单列表（分页）")
    public Result pageOrderByUid(@RequestParam("id") Long id,
                                 @RequestParam(value = "page", required = false, defaultValue = "1") Long page,
                                 @RequestParam(value = "limit", required = false, defaultValue = "99999") Long limit) {
        QueryWrapper<OrderGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("uid", id);
        wrapper.orderByDesc("startTime");
        Page<OrderGoods> page1 = new Page<>(page, limit);
        orderGoodsService.page(page1, wrapper);
        List<OrderGoods> orderList = orderGoodsService.orderGoodsSet(page1.getRecords());
        return new PageUtil<OrderGoods>().objectPageOrder(page1,orderList);
    }

    @Override
    @GetMapping("/getOrderByGuid")
    @ApiOperation("根据卖家id获取订单列表（分页）")
    public Result pageOrderByGuid(@RequestParam("id") Long id,
                                  @RequestParam(value = "page", required = false, defaultValue = "1") Long page,
                                  @RequestParam(value = "limit", required = false, defaultValue = "99999") Long limit) {
        Page<OrderGoods> myPage = new Page<>(page, limit);
        return orderGoodsService.pageOrderByGuid(myPage, id);
    }

    @Override
    @GetMapping("/getOrderByid")
    @ApiOperation("根据id获取订单详情")
    public Result getOrderById(@RequestParam("id") Long id) {
        OrderGoods orderGoods = orderGoodsService.getById(id);
        List<Long> ids = new ArrayList<>();
        ids.add(orderGoods.getUid());
        Result result = userService.getUserByIdList(ids);
        if (result.getCode() != 0) {
            return result;
        }
        List<User> userList = ResultUtil.listTrans(result.getData(), User.class);
        if (userList.size() < 1) {
            return Result.error("用户不存在");
        }
        orderGoods.setUser(userList.get(0));
        orderGoods.setGoods(goodsService.getById(orderGoods.getGid()));
        return Result.success(orderGoodsService.getById(id));
    }

    @Override
    @GetMapping("/getOrderBygid")
    @ApiOperation("根据商品id获取订单列表（分页）")
    public Result getOrderByGid(@RequestParam("id") Long id,
                                @RequestParam(value = "page", required = false, defaultValue = "1") Long page,
                                @RequestParam(value = "limit", required = false, defaultValue = "99999") Long limit) {
        QueryWrapper<OrderGoods> wrapper = new QueryWrapper<>();
        wrapper.eq("oid", id);
        Page<OrderGoods> page1 = new Page<>(page, limit);
        orderGoodsService.page(page1, wrapper);
        return new PageUtil<OrderGoods>().pageOrder(page1);
    }

    @Override
    @DeleteMapping("/deleteOrder")
    @ApiOperation("取消订单")
    @Transactional
    public Result deleteOrder(@RequestBody HashMap<String, Object> args) {
        Long id = Long.valueOf((String) args.get("id"));
        OrderGoods orderGoods = orderGoodsService.getById(id);
        if (orderGoods == null) {
            return Result.error("订单不存在");
        }
        int status = orderGoods.getStatus();
        if (status == OrderGoodsStatusUtil.SHIPPED.status || status == OrderGoodsStatusUtil.FINISH.status || status == OrderGoodsStatusUtil.STOP.status) {
            return Result.error("无法取消");
        }
        Long gid = orderGoods.getGid();
        Goods goods = goodsService.getById(gid);
        if (goods == null) {
            return Result.error("订单发生了错误");
        }
        Integer newNumber = goods.getNumber() + orderGoods.getNumber();
        goods.setNumber(newNumber);
        goods.setStatus(GoodStatusUtil.getGoodStatus(newNumber).status);
        orderGoods.setStatus(OrderGoodsStatusUtil.STOP.status);
        if (goodsService.updateById(goods) && orderGoodsService.updateById(orderGoods)) {
            return Result.success();
        } else {
            return Result.error("网络错误");
        }
    }


    @Override
    @PutMapping("/updateOrder")
    @ApiOperation("修改订单")
    @Transactional
    public Result updateOrderStatus(@RequestBody HashMap<String, Object> args) {
        Long id = (Long.valueOf((String) args.get("id")));
        OrderGoods orderGoods = orderGoodsService.getById(id);
        if (orderGoods == null) {
            return Result.error("订单不存在");
        }
        String address = (String) args.get("address");
        String sta = (String) args.get("status");
        Map<String, Object> map = new HashMap<>();
        map.put("id", orderGoods.getUid());
        map.put("money", orderGoods.getMoney());
        UpdateWrapper<OrderGoods> wrapper = new UpdateWrapper<>();
        wrapper.eq("id", id);
        if (sta.equals("setAddress")) {
            if (address == null) {
                return Result.error("地址不能为空");
            } else {
                wrapper.set("address", address);
            }
        } else if (sta.equals("PAID")) {
            if (orderGoods.getStatus() != OrderGoodsStatusUtil.UNPAID.status) {
                return Result.error("请勿重复支付");
            }

            Result result = userService.useMoney(map);
            if (result.getCode() != 0) {
                return result;
            }
            wrapper.set("status", OrderGoodsStatusUtil.UNSHIPPED.status);
        } else if (sta.equals("SHIPPED")) {
            if (orderGoods.getStatus() != OrderGoodsStatusUtil.UNSHIPPED.status) {
                return Result.error("暂时无法发货，请稍后重试");
            }
            wrapper.set("status", OrderGoodsStatusUtil.SHIPPED.status);
        } else if (sta.equals("FINISH")) {
            if ((orderGoods.getStatus() != OrderGoodsStatusUtil.SHIPPED.status)&&(orderGoods.getStatus() != OrderGoodsStatusUtil.UNSHIPPED.status)) {
                return Result.error("暂时无法签收，请重试");
            }
            Goods goods = goodsService.getById(orderGoods.getGid());
            map.put("id", goods.getUid());
            Result result = userService.addMoney(map);
            if (result.getCode() != 0) {
                return result;
            }
            wrapper.set("status", OrderGoodsStatusUtil.FINISH.status);
        }
        if (orderGoodsService.update(wrapper)) {
            return Result.success();
        } else {
            return Result.error("网络错误");
        }
    }

    @Override
    @GetMapping("/payOrder")
    @ApiOperation("微信支付")
    @Transactional
    public Result payOrder(@RequestParam("oid") Long id) {
        HashMap<String, Object> map = new HashMap<>();
        OrderGoods orderGoods = orderGoodsService.getById(id);
        if (orderGoods == null) {
            return Result.error("订单不存在");
        }
        map.put("id", String.valueOf(id));
        map.put("status", "PAID");
        HashMap<String, Object> userMap = new HashMap<>();
        userMap.put("id", orderGoods.getUid());
        userMap.put("money", orderGoods.getMoney());
        if (userService.addMoney(userMap).getCode() != 0) {
            return Result.error("支付失败");
        }
        return updateOrderStatus(map);
    }
}
